import math

from locust import task, between, SequentialTaskSet, events, HttpUser, LoadTestShape


class AppUsers(SequentialTaskSet):

    def on_start(self):
        print('----------开始执行子任务---------')

    def on_stop(self):
        print('---------结束执行子任务----------')
        print('\n')

    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
        "Accept-Encoding": "gzip, deflate, br",
        "authorization": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3ZWJUeXBlIjoiUEMiLCJleHAiOjE2MzA2NTYyMzIsInVzZXJJZCI6IjE0MTczNjMyMjY2ODI4Njc3MTMiLCJ1c2VyIjoie1wiY3JlYXRlQXRcIjpcIjIwMjEtMDctMjBUMTM6NTg6MjFcIixcImVuYWJsZVVzaW5nXCI6XCJVUFwiLFwiaWRcIjpcIjE0MTczNjMyMjY2ODI4Njc3MTNcIixcImludml0YXRpb25Db2RlXCI6XCJOVzVFRUFsQ1czNFFcIixcImxhc3RMb2dpblRpbWVcIjpcIjIwMjEtMDgtMjZUMTQ6MTY6NTlcIixcInBhcmVudElkXCI6XCIxXCIsXCJwYXNzd29yZFwiOlwiJDJhJDEwJHRpOUJnbVlBY0hJb25mSU1QM2R5R09TamlyQVpmRDBTTkhUVTdiRjV6RURBREJBalQ1Nm5hXCIsXCJwZXJtaXNzaW9uVmVyc2lvblwiOlwibWFpblwiLFwicGhvbmVcIjpcIjE4NzAwMDAwMTAwXCIsXCJ1cGRhdGVBdFwiOlwiMjAyMS0wOC0yNlQxNDoxNjo1OVwiLFwidXNlclNvdXJjZVwiOlwiUkVHSVNURVJcIixcInZpcEV4cGlyZVRpbWVcIjpcIjIwMjEtMTAtMTRUMDA6MDA6MDBcIixcInZpcEdyYWRlVHlwZVwiOlwiR0VORVJBTF9WSVBcIn0ifQ.KaiqGnnyua0jPJd9umCQ9wkHm4ZKUnfCbTvpvnVGZIc"
    }

    @task
    def index_2(self):
        with self.client.get(
                "https://www.baidu.com/",
                headers=self.header, catch_response=True,
                name='index_2') as response:
            if response.status_code != 200:
                response.failure('请求出问题了')
        print('index_2:', response.status_code)

    #
    # @task
    # def index_3(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/trend?searchTypes=IN_LIVE_NUMBER&searchTypes=LEAVE_LIVE_NUMBER&searchTypes=ON_LINE_NUMBER&warningType=IN_LIVE_NUMBER_UP&warningType=IN_LIVE_NUMBER_DOWN&warningType=COMMENT_NUMBER_DOWN&warningType=IN_LIVE_NUMBER&markPoints=true&warnPoints=true&timeType=MINUTE&pointsType=ADD_GOODS',
    #             headers=self.header, catch_response=True,
    #             name='index_3') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_3:', response.status_code)
    #
    # @task
    # def index_4(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/flow_source',
    #             headers=self.header, catch_response=True,
    #             name='index_4') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_4:', response.status_code)
    #
    # @task
    # def index_5(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/flow_trans',
    #             headers=self.header, catch_response=True,
    #             name='index_5') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_5:', response.status_code)
    #
    # @task
    # def index_6(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/comments?current=1&size=50',
    #             headers=self.header, catch_response=True,
    #             name='index_6') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_6:', response.status_code)
    #
    # @task
    # def index_7(self):
    #     with self.client.get(
    #             'https://api.test.dylive.aiyingli.com/buy_in/f/v1/live_room/6987643812373859086/goods?current=1&size=10',
    #             headers=self.header, catch_response=True,
    #             name='index_7') as response:
    #         if response.status_code != 200:
    #             response.failure('请求出问题了')
    #     print('index_7:', response.status_code)

    @task
    def stop(self):
        self.interrupt()


class StepLoadShaper(LoadTestShape):
    setp_time = 100
    setp_load = 1000
    spawn_rate = 10
    time_limit = 100

    def tick(self):
        run_time = self.get_run_time()

        if run_time > self.time_limit:
            return None

        current_step = math.floor(run_time / self.setp_time) + 1

        return current_step * self.setp_load, self.spawn_rate


class NewLinkToG(HttpUser):  # 模拟App用户
    # abstract = True   跳过执行该类
    # host = 'https://api.test.dylive.aiyingli.com'
    host = ''
    wait_time = between(10, 15)  # taskset类中每个def的执行间隔
    tasks = [AppUsers]


@events.test_start.add_listener
def on_test_start(**kwargs):  # 监测测试开始
    print('开始执行')


@events.test_stop.add_listener
def on_test_stop(environment, **kwargs):  # 监测测试结束
    print('执行结束')


@events.request_success.add_listener
def request_success(request_type, name, response_time, response_length, **kwargs):  # 监测请求成功
    result = 'success'
    print("{" + "'message':'{result}' ".format(
        result=result) + "'request_type':'{}','name':'{}','response_time':'{}','response_length':'{}'".format(
        request_type, name, response_time, response_length) + " }")


@events.request_failure.add_listener
def request_failure(request_type, name, response_time, response_length, **kwargs):  # 监测请求失败
    result = 'failure'
    print("{" + "'message':'{result}' ".format(
        result=result) + "'request_type':'{}','name':'{}','response_time':'{}','response_length':'{}'".format(
        request_type, name, response_time, response_length) + " }")


@events.quitting.add_listener
def _(environment, **kw):
    if environment.stats.total.fail_ratio > 0.01:
        print("Test failed due to failure ratio > 1%")
        environment.process_exit_code = 1
    elif environment.stats.total.avg_response_time > 200:
        print("Test failed due to average response time ratio > 200 ms")
        environment.process_exit_code = 1
    elif environment.stats.total.get_response_time_percentile(0.95) > 800:
        print("Test failed due to 95th percentile response time > 800 ms")
        environment.process_exit_code = 1
    else:
        environment.process_exit_code = 0


if __name__ == '__main__':
    import os

    os.system('locust -f locust-1.py')  # 主机
